package com.singzi.leetcode.N100;

import java.util.ArrayList;
import java.util.List;

public class T054 {
    public static void main(String[] args) {
        Solution54 solution54 = new Solution54();
        int [][]a = {
                {1, 2, 3, 4, 5},
                {6, 7, 8, 9, 10},
                {11, 12, 13, 14, 15},
                {16, 17, 18, 19, 20},
                {21, 22, 23, 24, 25} };

        System.out.println(solution54.spiralOrder(a));
    }
}
class Solution54 {
    public List<Integer> spiralOrder(int[][] matrix) {

        int[][]visited = new int[matrix.length][matrix[0].length];
        int flag = 1,i = 0, j = 0;
        addMatrix(flag, visited, matrix, i, j);
        return result;

    }
    List<Integer> result = new ArrayList<>();
    public void addMatrix(int flag, int[][]visited, int[][] matrix, int i, int j){
        if(result.size()==matrix.length*matrix[0].length) return;
        switch(flag)
        {
            case 1:{
                if(j >= matrix[0].length||visited[i][j]==1){
                    j--;
                    flag = 2;
                    i++;
                }
                else{
                    result.add(matrix[i][j]);
                    visited[i][j]=1;
                    j++;
                }
                addMatrix(flag, visited, matrix, i, j);
                break;

            }
            case 2:{
                if(i >= matrix.length||visited[i][j]==1){
                    i--;
                    flag = 3;
                    j--;
                }
                else{
                    result.add(matrix[i][j]);
                    visited[i][j]=1;
                    i++;
                }
                addMatrix(flag, visited, matrix, i, j);
                break;


            }
            case 3:{
                if(j < 0||visited[i][j]==1){
                    j++;
                    flag = 4;
                    i--;
                }
                else{
                    result.add(matrix[i][j]);
                    visited[i][j]=1;
                    j--;
                }
                addMatrix(flag, visited, matrix, i, j);
                break;
            }
            case 4:{
                if(i < 0||visited[i][j]==1){
                    i++;
                    flag = 1;
                    j++;
                }
                else{
                    result.add(matrix[i][j]);
                    visited[i][j]=1;
                    i--;
                }
                addMatrix(flag, visited, matrix, i, j);
                break;
            }


        }

    }
}